package account

import (
	"context"

	"user/internal/biz"
	"user/internal/model"
	"user/internal/svc"
	"user/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterResp, err error) {
	// todo: add your logic here and delete this line
	// 检查用户是否存在
	userModel := model.NewCustomerEntityModel(l.svcCtx.Mysql)
	user, err := userModel.FindOneByUsername(l.ctx, req.Username)
	if err != nil {
		return nil, biz.DBError
	}
	if user != nil {
		return nil, biz.AlreadyRegister
	}

	// 创建用户
	_, err = userModel.Insert(l.ctx, &model.CustomerEntity{
		Username: req.Username,
		Password: req.Password,
	})
	if err != nil {
		return nil, err
	}
	return
}
